<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="专栏名称:">
        <el-input v-model.trim="query.columnName" placeholder="专栏名称"></el-input>
      </el-form-item>
      <el-form-item label="审批状态:">
        <el-select v-model="query.approveStatus" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="1" label="待审批">待审批</el-option>
          <el-option value="2" label="审批通过">审批通过</el-option>
          <el-option value="3" label="审批拒绝">审批拒绝</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="fetchApplyColumnList">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button :disabled=" userRole !== 'SUPER_ADMIN' "
               size="small"
               type="danger"
               icon="el-icon-document-delete"
               @click="handleMultiDel()" style="margin-bottom: 20px;">删除</el-button>

    <!--  列表数据  -->
    <el-table :data="applyColumnData" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange"
              tooltip-effect="dark">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" label="序号" width="80" type="index"></el-table-column>
      <el-table-column align="center" prop="applyUserName" label="专栏创建人" width="200" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="columnName" label="专栏名称" width="300" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="columnIntro" label="专栏简介" width="500" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="approveTime" label="审批时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.approveTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="approveStatus" label="审批状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approveStatus === 1" type="info">待审批</el-tag>
          <el-tag v-if="scope.row.approveStatus === 2" type="success">审批通过</el-tag>
          <el-tag v-if="scope.row.approveStatus === 3" type="danger">审批拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="approveMessage" label="审批留言" width="200" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit"
                     type="success" size="mini"
                     v-if="scope.row.approveStatus === 1"
                     @click="handleApprove(scope.row.id, scope.row.columnName)">审批</el-button>
          <el-button icon="el-icon-document-delete"
                     :disabled=" userRole !== 'SUPER_ADMIN' "
                     type="danger" size="mini"
                     v-if="scope.row.approveStatus !== 1"
                     @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.pageNo"
                     :page-sizes="[10, 20, 50]"
                     :page-size="query.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="query.total">
      </el-pagination>
    </div>

    <el-drawer title="审批" :visible.sync="drawerVisible" direction="rtl" :before-close="handleClose" :wrapper-closable="false">
      <el-form :model="approveData" ref="formData" label-width="120px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="专栏名称：" prop="columnName">
          <el-input v-model="approveData.columnName" disabled />
        </el-form-item>
        <el-form-item label="审批状态：" prop="status">
          <el-radio-group v-model="approveData.approveStatus">
            <el-radio :label = 2 border>通过</el-radio>
            <el-radio :label = 3 border>拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="留言：" prop="approveMessage">
          <el-input v-model="approveData.approveMessage" placeholder="请输入留言" type="textarea" show-word-limit maxlength="50"/>
        </el-form-item>

      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="danger" plain @click="handleClose">取消</el-button>
        <el-button :disabled=" userRole !== 'SUPER_ADMIN' "
                   size="small" type="success"
                   @click="submit()" :loading="loading">提交</el-button>
      </el-row>
    </el-drawer>

  </div>
</template>
<script>
import { applyArticleList, approveArticle } from "@/api/approveArticle";
import { deleteApplyArticle } from "@/api/approveArticle";
import { dateFormat } from '@/utils/date';
import { getUserRole } from "@/utils/userToken";
import { applyColumnList, approveColumn, deleteColumn} from '@/api/approveColumn';

export default {
  data() {
    return {
      query: {
        approveStatus: "",
        columnName: "",
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      applyArticleData: [],
      applyColumnData: [],
      drawerVisible: false,
      approveData: {
        id: "",
        columnName: "",
        approveStatus: "",
        approveMessage: ""
      },
      loading: false,
      valid: true,
      checkedIds: [],
      userRole: ''
    }
  },

  created() {
    this.fetchApplyColumnList();
    this.userRole = getUserRole();
  },

  methods: {
    fetchApplyColumnList() {
      applyColumnList(this.query).then(res => {
        const { code, data, message } = res;
        if (code === 200) {
          this.applyColumnData = data.list;
          this.query.total = data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
        }
      })
    },

    // 审批
    handleApprove(id, columnName) {
      this.approveData.id = id;
      this.approveData.columnName = columnName;
      this.drawerVisible = true;
    },

    // 审批提交
    submit() {
      this.beforeSubmit();
      if (!this.valid) {
        this.valid = true;
        this.loading = false;
        return;
      }

      this.loading = true;
      approveColumn(this.approveData).then(res => {
        const { code, message } = res;
        if (code === 200) {
          this.$notify({
            title: '成功',
            message: '审批成功',
            type: 'success',
            duration: 1500
          });
          this.fetchApplyColumnList();
          this.handleClose();
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
          this.loading = false;
        }
      })
    },

    // 提交审批之前的判断
    beforeSubmit() {
      if (this.approveData.approveStatus !== 2 && this.approveData.approveStatus !== 3) {
        this.$notify.error({
          title: '错误',
          message: "请选择审批状态",
          duration: 1500
        });
        this.valid = false;
        return;
      }

      if (this.approveData.approveStatus === 3 && !this.approveData.approveMessage) {
        this.$notify.error({
          title: '错误',
          message: "当审批拒绝时，留言必填",
          duration: 1500
        });
        this.valid = false;
      }
    },

    handleDel(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          ids: []
        }
        data.ids.push(id);
        deleteColumn(data).then(res => {
          const { code, message } = res;
          if (code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchApplyColumnList();
        })
      }).catch(() => {
        // 取消删除

      });
    },

    handleMultiDel() {
      if (this.checkedIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一条记录',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          ids: []
        }
        data.ids = this.checkedIds;
        deleteColumn(data).then(res => {
          const { code, message } = res;
          if (code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchApplyColumnList();
          this.checkedIds = [];
        })
      }).catch(() => {
        // 取消删除
        console.log("取消")
        this.checkedIds = []
      });
    },

    handleSelectionChange(val) {
      this.checkedIds = [];
      let len = JSON.parse(JSON.stringify(val))
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedIds.push(len[i].id)
        }
      } else {
        this.checkedIds = len
      }
    },

    reload() {
      this.query.articleTitle = "";
      this.query.approveStatus = '';
      this.fetchApplyColumnList();
    },

    // 格式化日期
    getFormat(date){
      if (!date) {
        return date;
      }
      return dateFormat(date);
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchApplyColumnList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchApplyColumnList();
    },

    // 关闭审批的弹框
    handleClose() {
      this.loading = false;
      this.approveData.columnName = "";
      this.approveData.id = "";
      this.approveData.approveMessage = "";
      this.approveData.status = "";
      this.drawerVisible = false
    },

  },

}


</script>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 120px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
</style>
